package com.ezlcp.user.task;

import com.alibaba.fastjson2.JSON;
import com.ezlcp.commons.model.SysUser;
import com.ezlcp.commons.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author Elwin ZHANG
 * @description: 定时刷新Redis中的在线用户列表<br />
 * @date 2023/2/7 9:35
 */
@Component
@Slf4j
public class RefreshOnlineUserTask {
    /**
     * 是否计算在线用户
     */
    @Value("${ezlcp.online-user.calculate:false}")
    private boolean calculate;

    @Scheduled(fixedRate = TokenUtil.TOKEN_REFRESH_MINUTES * 60 * 1000, initialDelay = 300000)
    @Scheduled(fixedRate = 60 * 1000, initialDelay = 60000)
    public void refreshOnlineUserTask() {
        if (!calculate) {
            return;
        }
        log.info("=============定时刷新在线用户 开始===========");
        groupTokenByTenantId();
        log.info("=============定时刷新在线用户 结束===========");
    }

    /***
    * @description  把token按用公司分组，即为某公司的在线用户
    * @author Elwin ZHANG
    * @date 2023/2/7 16:36
    */
    private void groupTokenByTenantId(){
        var redisOp=TokenUtil.getRedisRepository();
        Map<String, Object> map = redisOp.getKeysValues("token");
        if (map == null) {
            return ;
        }
        HashMap<String, List<String>> resultMap=new HashMap<>();
        //遍历所有的token,按公司ID汇总
        for(var entry:map.entrySet()){
            String key=entry.getKey();
            SysUser user = JSON.parseObject(entry.getValue().toString(), SysUser.class);
            String tenantId= TokenUtil.dealTenantId(user.getTenantId());
            var list=resultMap.get(tenantId);
            if(list==null){
                list=new ArrayList<>();
                resultMap.put(tenantId,list);
            }
            list.add(key);
        }

        //将汇总的结果缓存起来
        redisOp.deleteByKeyPatten(TokenUtil.ONLINE_USER_KEY);
        for(var entry:resultMap.entrySet()) {
            String key= entry.getKey();
            var list=entry.getValue();
            String value=String.join(",",list);
            TokenUtil.setOnlineUsers(key,value);
        }
    }
}
